package com.laosg.framework.recaptcha;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONTokener;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.spring5.util.SpringContentTypeUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.UUID;

/**
 * <p>description: some thing </p>
 *
 * @author kevinruan@pano.im
 * @date 2019/12/28
 */
@RestController
@Data
@Slf4j
public class ApiController {

    @Value("${google.recaptcha.secret}")
    private  String SITE_SECRET;

    private static final String SECRET_PARAM = "secret";
    private static final String RESPONSE_PARAM = "response";
    private static final String G_RECAPTCHA_RESPONSE = "g-recaptcha-response";
    private static final String SITE_VERIFY_URL = "https://www.recaptcha.net/recaptcha/api/siteverify";

    @Autowired
    private RestTemplate restTemplate;

    private JSONObject performRecaptchaSiteVerify(String recaptchaResponseToken)
            throws IOException {
        URL url = new URL(SITE_VERIFY_URL);
        StringBuilder postData = new StringBuilder();
        addParam(postData, SECRET_PARAM, SITE_SECRET);
        addParam(postData, RESPONSE_PARAM, recaptchaResponseToken);

        return postAndParseJSON(url, postData.toString());
    }

    private JSONObject postAndParseJSON(URL url, String postData) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty(
                "Content-Type", "application/x-www-form-urlencoded");
        urlConnection.setRequestProperty(
                "charset", StandardCharsets.UTF_8.displayName());
        urlConnection.setRequestProperty(
                "Content-Length", Integer.toString(postData.length()));
        urlConnection.setUseCaches(false);
        urlConnection.getOutputStream()
                .write(postData.getBytes(StandardCharsets.UTF_8));
        JSONTokener jsonTokener = new JSONTokener(urlConnection.getInputStream());
        return new JSONObject(jsonTokener);
    }

    private StringBuilder addParam(
            StringBuilder postData, String param, String value)
            throws UnsupportedEncodingException {
        if (postData.length() != 0) {
            postData.append("&");
        }
        return postData.append(
                String.format("%s=%s",
                        URLEncoder.encode(param, StandardCharsets.UTF_8.displayName()),
                        URLEncoder.encode(value, StandardCharsets.UTF_8.displayName())));
    }

    /**
     * {
     *   "success": true|false,      // whether this request was a valid reCAPTCHA token for your site
     *   "score": number             // the score for this request (0.0 - 1.0)
     *   "action": string            // the action name for this request (important to verify)
     *   "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
     *   "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
     *   "error-codes": [...]        // optional
     * }
     * @param req
     * @return
     */
    @PostMapping("token")
    public String get(HttpServletRequest req) throws IOException {
        String parameter = req.getParameter(G_RECAPTCHA_RESPONSE);
        String verity = req.getParameter("username");


//        HttpHeaders headers = new HttpHeaders();
//        HttpMethod method = HttpMethod.POST;
//        JSONObject postParameters = new JSONObject();
////        MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
//        postParameters.put("email", "pfqurb39708@chacuo.net");//qa
//        postParameters.put("password","12345678");
//        postParameters.put("phone","18550633486");
//        postParameters.put("smsCode",verity);
//        postParameters.put("usage","reg");
////            postParameters.add("username", "lao4ji@163.com");
////            postParameters.add("password","Q123456p");
//        postParameters.put("g-recaptcha-response",parameter);
//
//        // 以表单的方式提交
//        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//
//        headers.set("Tracking-Id", UUID.randomUUID().toString().replaceAll("-", ""));
//        //将请求头部和参数合成一个请求
//        HttpEntity requestEntity = new HttpEntity(postParameters.toString(), headers);
//        log.info("requestEntity:{}",requestEntity);
//        String authURL = "http://localhost:8010/sirius/accounts";
//
//        ResponseEntity<Object> response = restTemplate.exchange(authURL, method, requestEntity, Object.class);

// -----------------------------------

//        String password = req.getParameter("password");
        JSONObject jsonObject = null;
////        JSONObject params = new JSONObject();
////        params.put(SECRET_PARAM, SITE_SECRET);
////        params.put(RESPONSE_PARAM,parameter);
//        try {
            MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
            postParameters.add(SECRET_PARAM, SITE_SECRET);
            postParameters.add(RESPONSE_PARAM,parameter);
//
            jsonObject = performRecaptchaSiteVerify(parameter);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity httpEntity = new HttpEntity(postParameters,httpHeaders);
            ResponseEntity<Object> exchange = restTemplate.exchange(SITE_VERIFY_URL, HttpMethod.POST, httpEntity, Object.class);
//            log.info("response:{}",exchange.getBody());
//            log.info("result:{}",JSONUtil.getByPath(JSONUtil.parse(exchange.getBody()),"success"));
// -----------------------------------
//            HttpHeaders headers = new HttpHeaders();
//            HttpMethod method = HttpMethod.POST;
//
//           MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
//        postParameters.add("username", "9jy61dpa@linshiyouxiang.net");//qa
//        postParameters.add("password","123456");
////            postParameters.add("username", "lao4ji@163.com");
////            postParameters.add("password","Q123456p");
//            postParameters.add("g-recaptcha-response",parameter);
//
//            // 以表单的方式提交
//            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//
//            headers.set("Tracking-Id", UUID.randomUUID().toString().replaceAll("-", ""));
//            //将请求头部和参数合成一个请求
//            HttpEntity requestEntity = new HttpEntity(postParameters, headers);
//            log.info("requestEntity:{}",requestEntity);
//            String authURL = "http://10.0.4.70:8010/sirius/login";
////            String authURL = "http://localhost:8010/sirius/login";
////            String authURL = "http://localhost:8010/sirius/accounts/retrievePassword?email=lao4ji@163.com&g-recaptcha-response="+parameter;
//
//            ResponseEntity<Object> response = restTemplate.exchange(authURL, method, requestEntity, Object.class);

//        Object object = restTemplate.getForObject(authURL, Object.class, postParameters);

//        log.info("res:{}->{}",response,response.getBody());
        log.info("res:{}->{}",exchange,exchange.getBody());




//        boolean success = jsonObject.getBoolean("success");

        return "ss";
    }
}
